import sys
import System
import System.Threading
import clr
import time
import threading
import thread

import napake
import nadgradnja
import SocketServer

clr.AddReferenceByPartialName("PresentationCore")
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("WindowsBase")
clr.AddReferenceByPartialName("IronPython")
clr.AddReferenceByPartialName("Microsoft.Scripting")
clr.AddReference('System.Drawing')
clr.AddReferenceToFileAndPath("IronPython.Wpf.dll")

from System import Action, AppDomain, UnhandledExceptionEventHandler, Windows
from System.Collections import *
clr.AddReferenceByPartialName('MySql.Data')
from MySql.Data.MySqlClient import * 
clr.AddReference('System.Data')
from System.Data.SqlClient import SqlConnection
from System.Threading import *
from System.Threading.Tasks import *
from System.Windows.Threading import *
from System.Text.RegularExpressions import *
clr.AddReference("SAP_dll")
from SAP_dll import *
from System.ComponentModel import BackgroundWorker
from System.Windows import Window
from napake import *
from System.Windows.Controls import *
from System.Drawing import *

class ObjectLocker(object):
      def __init__(self, obj):
              self.obj = obj
      def __enter__(self):
              global stevec_poizvedb
              stevec_poizvedb += 1
              Monitor.Enter(self.obj)
      def __exit__(self, *args):
              global stevec_poizvedb
              stevec_poizvedb -= 1
              Monitor.Exit(self.obj)

IT_VERZIJA = "0A1"

datum_format = 'yyy-MM-dd hh:mm:ss' # format datuma
ID_izdelka = None
gl_insert_stavek = None
stevec_poizvedb = 0

conStrNtpe1 = 'server=ntpe1; userid=purkat; password=purkat; database=sledljivost;'
#dbNtpe1 = MySqlConnection(conStrNtpe1) 

conStrPris = 'Data Source=vmie3;initial catalog=KAKOVOST;user id=uporabnik;password=uporabnik; Connect Timeout=30'
#dbPris = SqlConnection(conStrPris)

# UNHANDLED EXCEPTION
def handler(sender, event):
    debug.TraceDbg("Unhandled exception v skripti!", event.ExceptionObject, "Error")
    print event.ExceptionObject

#AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionEventHandler(handler)

Application.ThreadException += ThreadExceptionEventHandler(handler)
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)

#
# POVEZAVA Z SAP
#
def poizvedbaSAP(tip, vrednost):    # Vrne array (0) Procesna, (1) Serijska
    l = ArrayList()
    ProcesnaSAP = 'n\a'
    SerijskaSAP = 'n\a'
    with ObjectLocker(SAP400):
        barva_obrazca('Blue')
        try:
            if (tip == 'P'):    # Imamo procesno
                ProcesnaSAP = vrednost
                try:
                    SerijskaSAP = SAP400().getSerial(vrednost.ToString().Substring(0,9) + 'A')
                except:
                    SerijskaSAP = SAP400().getSerial(vrednost.ToString().Substring(0,9) + 'B')
            if (tip == 'S'):    # Imamo serijsko
                SerijskaSAP = vrednost
                ProcesnaSAP = SAP400().getProcess(vrednost)
            l.Add(ProcesnaSAP)
            l.Add(SerijskaSAP)
        except Exception, e:
            debug.TraceDbg("Poizvedba na SAP neuspesna!", e.message.ToString(), "Warning")
            System.Threading.Thread.Sleep(2000)
            if (tip == 'P'):
                l.Add(vrednost)
                l.Add(e.message.ToString())
            if (tip == 'S'):
                l.Add(e.message.ToString())
                l.Add(vrednost)
        barva_obrazca('None')
        return l
#
# POVEZAVA Z NTPE1
#
def poizvedbaNTPE(stavek, izhod):
    dbNtpe1 = MySqlConnection(conStrNtpe1) 
    l = ArrayList()
    i=0
    print "NTPE: %s" %stavek
    with ObjectLocker(dbNtpe1):
        while dbNtpe1.State.ToString() != System.Data.ConnectionState.Open.ToString():  
            try:
              dbNtpe1.Open()
              cmd = dbNtpe1.CreateCommand() 
              cmd.CommandText = stavek
              r = cmd.ExecuteReader () 
              l = ArrayList()
              while r.Read (): 
                  vrednost = izhod
                  for x in range(r.FieldCount):
                      vrednost = vrednost.replace("{%s}" %r.GetName(x) ,r[x].ToString())
                  l.Add(vrednost)
              r.Close () 
              barva_obrazca('None')
            except Exception, e:
              debug.TraceDbg("Povezava na NTPE1 neuspesna!", e.message.ToString(), "Warning")
              System.Threading.Thread.Sleep(2000)
              if (i<2):
                barva_obrazca('Orange')
              else:
                barva_obrazca('Red')
              i=i+1
        dbNtpe1.Close () 
        return l

#
# POVEZAVA Z PRIS
#
def poizvedbaPRIS(stavek, izhod):
    dbPris = SqlConnection(conStrPris)
    l = ArrayList()
    i = 0
    print "PRIS: %s" %stavek
    #with ObjectLocker(dbPris):
    while dbPris.State.ToString() != System.Data.ConnectionState.Open.ToString():
        try:
            dbPris.Open()
            cmd = dbPris.CreateCommand() 
            cmd.CommandText = stavek
            r = cmd.ExecuteReader () 
            l = ArrayList()
            while r.Read (): 
                vrednost = izhod
                for x in range(r.FieldCount):
                    vrednost = vrednost.replace("{%s}" %r.GetName(x) ,r[x].ToString())
                l.Add(vrednost)
            r.Close () 
            barva_obrazca('None')
        except Exception, e:
            debug.TraceDbg("Povezava na PRIS neuspesna!", "Stavek: %s\n%s" %(stavek, e.message.ToString()), "Warning")
            System.Threading.Thread.Sleep(1000)
            if (i<2):
                barva_obrazca('Orange')
            else:
                barva_obrazca('Red')
            i=i+1
    dbPris.Close () 
    return l

#def prenos():

#    procesne = poizvedbaNTPE("SELECT  `Procesna`  FROM `sledljivost`.`spremni_list_izdelka` ORDER BY `Datum`;", "{Procesna}")
#    delovninalogi = poizvedbaNTPE("SELECT  `DelNalog`  FROM `sledljivost`.`spremni_list_izdelka` ORDER BY `Datum`;", "{DelNalog}")
#    operacijaoperater = poizvedbaNTPE("SELECT  `Operacija`  FROM `sledljivost`.`spremni_list_izdelka` ORDER BY `Datum`;", "{Operacija}")
#    operacija = ArrayList()
#    operater = ArrayList()
#    for xxx in operacijaoperater:
#        operacija.Add(xxx.Substring(0, xxx.IndexOfAny("0123456789".ToCharArray())).Trim())
#        operater.Add(xxx.Substring(xxx.IndexOfAny("0123456789".ToCharArray())).Trim())
#    print '%s' %procesne.Count
#    i=0
#    #for i in range(40): 
#    for xxx in procesne:
#        print '%s %s %s %s' %(procesne[i], delovninalogi[i], operacija[i], operater[i])
#        poizvedbaPRIS("UPDATE \"SPREMNILISTIZDELKA\" (\"PROCESNA\", \"NALOG\", \"DATUM\", \"OPERACIJA\", \"OPERATER\", \"REZULTAT\") VALUES ('%s', '%s', '2013-02-26 10:55:00', '%s', %s, 0);" %(procesne[i], delovninalogi[i], operacija[i], operater[i]),'')
#        i+=1

def prenos():
    procesne = poizvedbaNTPE("SELECT  `Procesna`  FROM `sledljivost`.`spremni_list_izdelka` WHERE `DelNalog` = \"%s\" ORDER BY `Datum`;" %(obrazec.comboBox_delnalogi.SelectedItem.ToString()), "{Procesna}")
    for xxx in procesne:
        ID = poizvedbaPRIS("INSERT INTO SPREMNILISTIZDELKA (PROCESNA, SERIJSKA, NALOG, DATUM, OPERACIJA, OPERATER, REZULTAT, TEST) VALUES ('%sB', '%s', '%s', '%s', '%s', %s, %s, '%s'); SELECT SCOPE_IDENTITY();"
                    %(xxx.ToString(), obrazec.label1_serijska_vobdelavi.Content, obrazec.comboBox_delnalogi.SelectedItem.ToString(), DateTime.Now.ToString(datum_format),
                    obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_operaterji.SelectedItem.ToString().Substring(0, obrazec.comboBox_operaterji.SelectedItem.ToString().IndexOf('\t')),
                    0, obrazec.label1_rezultat_vobdelavi.Content), "{}")
        poizvedbaNTPE("UPDATE `sledljivost`.`spremni_list_izdelka` SET `Rezultat` = 'PASS_p' WHERE `Procesna` LIKE '%s%%';" %(xxx), "{d}")

    osvezi_kolicine()


def bg_Poizvedba_NTPE(sender, args):
    tmp = poizvedbaNTPE(args.Argument[0], args.Argument[1])
    args.Result = tmp

def bg_Poizvedba_PRIS(sender, args):
    tmp = poizvedbaPRIS(args.Argument[0], args.Argument[1])
    args.Result = tmp

def bg_Poizvedba_SAP(sender, args):
    tmp = poizvedbaSAP(args.Argument[0], args.Argument[1])
    args.Result = tmp

########################################################
########################################################
########################################################
debug.TraceDbg("Skripta verzija %s" %(IT_VERZIJA), None, "Info")

def barva_obrazca(barva):    #{Red, Blue, Green};
    obrazec.Dispatcher.Invoke(DispatcherPriority.Background, Action[object](obrazec.ChangeGrid), barva)

def seznam_izdelkov(izdelki):
    obrazec.label_status.Content = 'Poizvedba za izdelki'
    obrazec.comboBox_izdelki.ItemsSource = izdelki

def seznam_operacij(operacije):
    obrazec.label_status.Content = 'Poizvedba za operacijami'
    obrazec.comboBox_operacije.ItemsSource = operacije

def seznam_operaterjev(operaterji):
    obrazec.label_status.Content = 'Poizvedba za operaterji'
    obrazec.comboBox_operaterji.ItemsSource = operaterji

def bg_Sprememba_cb_delnalogi(sender, args):
    obrazec.label_status.Content = 'Poizvedba za delovnimi nalogi'
    izdelek = args.Result
    obrazec.comboBox_delnalogi.ItemsSource = izdelek 

def bg_Sprememba_cb_napake(sender, args):
    obrazec.label_status.Content = 'Poizvedba za seznamom napak'
    napake = args.Result
    obrazec.comboBox_pozicije_napake.ItemsSource = napake

def dn_changed(sender, args):
    osvezi_kolicine()

def operacije_changed(sender, args):
    brisiznake()
    osvezi_kolicine()

def izdelek_changed(sender, args):
    #pobrisemo seznam delovnih nalogov in kosovnico
    obrazec.comboBox_delnalogi.ItemsSource = None
    obrazec.comboBox_delnalogi.Items.Clear()
    obrazec.comboBox_pozicije_napake.ItemsSource = None
    obrazec.comboBox_pozicije_napake.Items.Clear()
    #delovni nalogi
    worker_dn = BackgroundWorker()
    worker_dn.DoWork += bg_Poizvedba_NTPE
    worker_dn.RunWorkerCompleted += bg_Sprememba_cb_delnalogi
    worker_dn.RunWorkerAsync(["SELECT DISTINCT `DN` FROM `sledljivost`.`asysaba04` WHERE `Program` = '%s'" %obrazec.comboBox_izdelki.SelectedItem.ToString(), "{DN}"])
    #napake
    worker_napake = BackgroundWorker()
    worker_napake.DoWork += bg_Poizvedba_PRIS
    worker_napake.RunWorkerCompleted += bg_Sprememba_cb_napake
    worker_napake.RunWorkerAsync(["SELECT [KAKOVOST].[dbo].[KOSOVNICE].[POZICIJA] FROM [KAKOVOST].[dbo].[KOSOVNICE], [KAKOVOST].[dbo].[SEZMATERIALOV] WHERE [KAKOVOST].[dbo].[KOSOVNICE].[KODA]=(SELECT [ID] FROM [KAKOVOST].[dbo].[SEZKOD] WHERE [KODA]='%s') AND [KAKOVOST].[dbo].[SEZMATERIALOV].[ID] = [KAKOVOST].[dbo].[KOSOVNICE].[MAT];" %obrazec.comboBox_izdelki.SelectedItem.ToString(), "{POZICIJA}"])

def bg_Sprememba_tb_identnapake(sender, args):
    obrazec.label_status.Content = 'Poizvedba za identom napake'
    ident = args.Result
    obrazec.textBox_ident_napake.Text = ident[0]

def bg_Sprememba_tb_material(sender, args):
    obrazec.label_status.Content = 'Poizvedba za materialom'
    material = args.Result
    obrazec.textBox_material_napake.Text = material[0]

def bg_Sprememba_cb_napakeopis(sender, args):
    obrazec.label_status.Content = 'Poizvedba za opisi napak'
    napake = args.Result
    obrazec.comboBox_napake_napake.ItemsSource = napake 

def bg_Sprememba_cb_napakeopis_id(sender, args):
    obrazec.label_status.Content = 'Poizvedba za ID opisov napak'
    napake = args.Result
    obrazec.comboBox_napake_napake.Tag = napake 

def napake_napake_changed(sender, args):
    try:
        ID = obrazec.comboBox_napake_napake.Tag
        print "ID napake %s je %s !" %(obrazec.comboBox_napake_napake.SelectedItem.ToString(), ID[obrazec.comboBox_napake_napake.SelectedIndex])
    except Exception, e:
        print e.ToString()

def pozicija_napake_changed(sender, args):
    #Pobrisemo stare napake
    obrazec.textBox_ident_napake.Text = ''
    obrazec.textBox_material_napake.Text = ''
    obrazec.comboBox_napake_napake.ItemsSource = None
    obrazec.comboBox_napake_napake.Items.Clear() 
    if (obrazec.comboBox_pozicije_napake.SelectedItem == None):
        return
    #ident
    worker_ident = BackgroundWorker()
    worker_ident.DoWork += bg_Poizvedba_PRIS
    worker_ident.RunWorkerCompleted += bg_Sprememba_tb_identnapake
    worker_ident.RunWorkerAsync(["SELECT [KAKOVOST].[dbo].[KOSOVNICE].[IDENT] FROM [KAKOVOST].[dbo].[KOSOVNICE], [KAKOVOST].[dbo].[SEZMATERIALOV] WHERE [KAKOVOST].[dbo].[KOSOVNICE].[KODA]=(SELECT [ID] FROM [KAKOVOST].[dbo].[SEZKOD] WHERE [KODA]='%s') AND [KAKOVOST].[dbo].[SEZMATERIALOV].[ID] = [KAKOVOST].[dbo].[KOSOVNICE].[MAT] AND [KAKOVOST].[dbo].[KOSOVNICE].[POZICIJA] = '%s';" %(obrazec.comboBox_izdelki.SelectedItem.ToString(), obrazec.comboBox_pozicije_napake.SelectedItem.ToString()), "{IDENT}"])
    #material
    worker_mat = BackgroundWorker()
    worker_mat.DoWork += bg_Poizvedba_PRIS
    worker_mat.RunWorkerCompleted += bg_Sprememba_tb_material
    worker_mat.RunWorkerAsync(["SELECT [MATERIAL] FROM [KAKOVOST].[dbo].[SEZMATERIALOV] WHERE ID=(SELECT [KAKOVOST].[dbo].[KOSOVNICE].[MAT] FROM [KAKOVOST].[dbo].[KOSOVNICE] WHERE [KAKOVOST].[dbo].[KOSOVNICE].[POZICIJA] = '%s' AND [KAKOVOST].[dbo].[KOSOVNICE].[KODA] = (SELECT [KAKOVOST].[dbo].[SEZKOD].[ID] FROM [KAKOVOST].[dbo].[SEZKOD] WHERE [KAKOVOST].[dbo].[SEZKOD].[KODA]='%s'));" %(obrazec.comboBox_pozicije_napake.SelectedItem.ToString(), obrazec.comboBox_izdelki.SelectedItem.ToString()), "{MATERIAL}"])
    #napake
    worker_napakeopis = BackgroundWorker()
    worker_napakeopis.DoWork += bg_Poizvedba_PRIS
    worker_napakeopis.RunWorkerCompleted += bg_Sprememba_cb_napakeopis
    worker_napakeopis.RunWorkerAsync(["SELECT [NAPAK], [OPIS] FROM [KAKOVOST].[dbo].[SEZNAPAKN] WHERE [KRAJ]=(SELECT [KAKOVOST].[dbo].[KOSOVNICE].[KRAJ] FROM [KAKOVOST].[dbo].[KOSOVNICE] WHERE [KAKOVOST].[dbo].[KOSOVNICE].[POZICIJA] = '%s' AND [KAKOVOST].[dbo].[KOSOVNICE].[KODA] = (SELECT [KAKOVOST].[dbo].[SEZKOD].[ID] FROM [KAKOVOST].[dbo].[SEZKOD] WHERE [KAKOVOST].[dbo].[SEZKOD].[KODA]='%s')) ORDER BY [NAPAK]; "%(obrazec.comboBox_pozicije_napake.SelectedItem.ToString(), obrazec.comboBox_izdelki.SelectedItem.ToString()), "{NAPAK}: {OPIS}"])
    worker_napakeopis_id = BackgroundWorker()
    worker_napakeopis_id.DoWork += bg_Poizvedba_PRIS
    worker_napakeopis_id.RunWorkerCompleted += bg_Sprememba_cb_napakeopis_id
    worker_napakeopis_id.RunWorkerAsync(["SELECT [OLD] FROM [KAKOVOST].[dbo].[SEZNAPAKN] WHERE [KRAJ]=(SELECT [KAKOVOST].[dbo].[KOSOVNICE].[KRAJ] FROM [KAKOVOST].[dbo].[KOSOVNICE] WHERE [KAKOVOST].[dbo].[KOSOVNICE].[POZICIJA] = '%s' AND [KAKOVOST].[dbo].[KOSOVNICE].[KODA] = (SELECT [KAKOVOST].[dbo].[SEZKOD].[ID] FROM [KAKOVOST].[dbo].[SEZKOD] WHERE [KAKOVOST].[dbo].[SEZKOD].[KODA]='%s')) ORDER BY [NAPAK]; "%(obrazec.comboBox_pozicije_napake.SelectedItem.ToString(), obrazec.comboBox_izdelki.SelectedItem.ToString()), "{OLD}"])

def osvezi_kolicine():
    try:
        worker_kolicine = BackgroundWorker()
        worker_kolicine.DoWork += bg_Poizvedba_PRIS
        worker_kolicine.RunWorkerCompleted += bg_osvezi_kolicine
        stavek_pass = "SELECT COUNT(*) FROM (SELECT PROCESNA, MAX(DATUM) as MaxTime FROM KAKOVOST.dbo.SPREMNILISTIZDELKA GROUP BY PROCESNA) r INNER JOIN SPREMNILISTIZDELKA t ON t.PROCESNA = r.PROCESNA AND t.DATUM = r.MaxTime WHERE OPERACIJA IN ('%s') AND NALOG IN ('%s') and REZULTAT = 0" %(obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_delnalogi.SelectedItem.ToString())
        stavek_fail = "SELECT COUNT(*) FROM (SELECT PROCESNA, MAX(DATUM) as MaxTime FROM KAKOVOST.dbo.SPREMNILISTIZDELKA GROUP BY PROCESNA) r INNER JOIN SPREMNILISTIZDELKA t ON t.PROCESNA = r.PROCESNA AND t.DATUM = r.MaxTime WHERE OPERACIJA IN ('%s') AND NALOG IN ('%s') and REZULTAT = 2" %(obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_delnalogi.SelectedItem.ToString())
        stavek_karantena = "SELECT COUNT(*) FROM (SELECT PROCESNA, MAX(DATUM) as MaxTime FROM KAKOVOST.dbo.SPREMNILISTIZDELKA GROUP BY PROCESNA) r INNER JOIN SPREMNILISTIZDELKA t ON t.PROCESNA = r.PROCESNA AND t.DATUM = r.MaxTime WHERE NALOG IN ('%s') and REZULTAT = 5" %(obrazec.comboBox_delnalogi.SelectedItem.ToString())
        stavek_nalog = "SELECT STMODULOV FROM KAKOVOST.dbo.DELNALOGI WHERE DELNALOG IN ('%s')" %(obrazec.comboBox_delnalogi.SelectedItem.ToString())
        worker_kolicine.RunWorkerAsync(["SELECT (%s) as st, (%s) as pass, (%s) as fail, (%s) as karantena" %(stavek_nalog, stavek_pass, stavek_fail, stavek_karantena), "{st} {pass} {fail} {karantena}"])
    except Exception, e:
        brisiznake()
        debug.TraceDbg("Ne morem osveziti kolicin !", e.message.ToString(), "Warning")

def bg_osvezi_kolicine(sender, args):
    #print "Osvezujem kolicine ..."
    global lb_nalog
    global lb_pass
    global lb_fail
    global lb_out
    global lb_todo
    
    rezultat = args.Result[0].ToString().Split(' ')
    lb_nalog.Content = rezultat[0]
    lb_pass.Content = rezultat[1]
    lb_fail.Content = rezultat[2]
    lb_out.Content = rezultat[3]
    lb_todo.Content = int(rezultat[0].ToString()) - int(rezultat[1].ToString()) - int(rezultat[2].ToString()) - int(rezultat[3].ToString())

def socketxx():
    obrazec.label1_rezultat_vobdelavi.Content="PASS"

def dummyprocesna_changed(sender, args):
    if (obrazec.textBox_dummyprocesna.Text.Length != 10):
        return
    else:
        try:
             
            obrazec.label_status.Content = 'Poizvedba za izdelkom ter delovnim nalogom %s' %obrazec.textBox_dummyprocesna.Text
            izdelek = poizvedbaNTPE("SELECT `Program` FROM `sledljivost`.`asysaba04` WHERE `Procesna` = '%s'" %obrazec.textBox_dummyprocesna.Text, "{Program}")[0]
            delnalog = poizvedbaNTPE("SELECT `DN` FROM `sledljivost`.`asysaba04` WHERE `Procesna` = '%s'" %obrazec.textBox_dummyprocesna.Text, "{DN}")[0]
            debug.TraceDbg("Informacije za %s" %obrazec.textBox_dummyprocesna.Text, "Izdelek: %s\nDN: %s" %(izdelek, delnalog), "Info")
            obrazec.comboBox_izdelki.SelectedItem = izdelek
            obrazec.comboBox_delnalogi.SelectedItem = delnalog
        except Exception, e:
            debug.TraceDbg("Procesna %s ne obstaja!" %obrazec.textBox_dummyprocesna.Text, e.message.ToString(), "Warning")
            stop("Procesna %s ne obstaja!" %obrazec.textBox_dummyprocesna.Text, 1)

def StartHooker():
    debug.checkBox_keyhooker.IsChecked = True

def bg_Podatki_SAP(sender, args):
    ident = args.Result       
    preveriProcesnaVDN(ident[0])
    obrazec.label1_procesna_vobdelavi.Content = ident[0]
    obrazec.label1_serijska_vobdelavi.Content = ident[1]
    debug.TraceDbg("SAP poizvedba uspela: PN %s SN %s!" %(ident[0], ident[1]), None, "Info")


def hookerchangedP(sender, args):
    if (serialP.IsMatch(debug.textBox_logging.Text)):
        procesnast = serialP.Match(debug.textBox_logging.Text).Value
        debug.TraceDbg("Procesna se je ujela %s!" %procesnast, None, "Info")
        ID_izdelka = None
        worker_sap = BackgroundWorker()
        worker_sap.DoWork += bg_Poizvedba_SAP
        worker_sap.RunWorkerCompleted += bg_Podatki_SAP
        worker_sap.RunWorkerAsync(['P',procesnast])
        debug.textBox_logging.Clear()

def hookerchangedZ(sender, args):
    if (serialZ.IsMatch(debug.textBox_logging.Text)):
        serijskast = serialZ.Match(debug.textBox_logging.Text).Value
        debug.TraceDbg("Serijska se je ujela %s!" %serijskast, None, "Info")
        ID_izdelka = None
        worker_sap = BackgroundWorker()
        worker_sap.DoWork += bg_Poizvedba_SAP
        worker_sap.RunWorkerCompleted += bg_Podatki_SAP
        worker_sap.RunWorkerAsync(['S',serijskast])
        debug.textBox_logging.Clear()

def socketpodatek(serst):
        debug.TraceDbg("Socket je sporocil novega obdelovanca %s!" %serst, None, "Info")
        ID_izdelka = None
        worker_sap = BackgroundWorker()
        worker_sap.DoWork += bg_Poizvedba_SAP
        worker_sap.RunWorkerCompleted += bg_Podatki_SAP
        worker_sap.RunWorkerAsync(['S',serst])
        debug.textBox_logging.Clear()

def preveriProcesnaVDN(procesna, brisistanje=1): #preveri ce je vnesena procesna del izbranega izdelka in del. naloga
    try:
        izdelek_iz_procesne = poizvedbaNTPE("SELECT `Program` FROM `sledljivost`.`asysaba04` WHERE `Procesna` LIKE '%s%%'" %procesna.Substring(0,9), "{Program}")
        dn_iz_procesne = poizvedbaNTPE("SELECT `DN` FROM `sledljivost`.`asysaba04` WHERE `Procesna` LIKE '%s%%'" %procesna.Substring(0,9), "{DN}")
        napake_s = 0
        napake_w = 0
        napake_i = 0
        Opis_Napake_s = ''
        Opis_Napake_w = ''
        Opis_Napake_i = ''
        if (brisistanje):
            brisiznake()
        # Preverba izbranega DN (+ERROR)
        if (izdelek_iz_procesne.Count > 0 and dn_iz_procesne.Count > 0):
            if (izdelek_iz_procesne[0] != obrazec.comboBox_izdelki.Text):
                napake_s+=1
                Opis_Napake_s+='NTPE: Izdelek (%s) ne ustreza testnemu postopku (%s)\n' %(procesna, izdelek_iz_procesne[0])
            if (dn_iz_procesne[0] != obrazec.comboBox_delnalogi.Text):
                napake_s+=1
                Opis_Napake_s+='NTPE: Izdelek (%s) ni del delovnega naloga (%s)\n' %(procesna, dn_iz_procesne[0])
        else:
            napake_s+=1
            Opis_Napake_s+='NTPE: Procesna (%s) ne obstaja v sistemu!\n' %procesna

        # Ali je imela plosca napake na predhodnih operacijah (+WARNING)
        for napake in poizvedbaPRIS("SELECT ID, OPERACIJA, POZICIJA, NAPAKA FROM KAKOVOST.dbo.SPREMNILISTNAPAK WHERE PROCESNA = '%s';" %(procesna), "{ID},{OPERACIJA},{POZICIJA},{NAPAKA}"):
            napake_w+=1
            podatki = napake.Split(',')
            Opis_Napake_w+='Napaka na operaciji %s: pozicija %s, napaka %s: %s\n' %(podatki[1], podatki[2], poizvedbaPRIS("SELECT NAPAK FROM KAKOVOST.dbo.SEZNAPAKN WHERE OLD='%s'" %podatki[3], "{NAPAK}")[0], poizvedbaPRIS("SELECT OPIS FROM KAKOVOST.dbo.SEZNAPAKN WHERE OLD='%s'" %podatki[3], "{OPIS}")[0])

        # Ali je bila plosca ze prej stestirana (+INFO)
        stevilotestiranj = int(poizvedbaPRIS("SELECT COUNT(*) FROM KAKOVOST.dbo.SPREMNILISTIZDELKA WHERE PROCESNA LIKE '%s%%' AND OPERACIJA = '%s';" %(procesna.ToString().Substring(0,9),  obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t'))), "{}")[0])
        if (stevilotestiranj > 0):
            napake_i+=1
            Opis_Napake_i+='Plosca je ze bila %sx na tem testu!\n' %stevilotestiranj

    
        if (napake_s > 0):
            stop(Opis_Napake_s, 1)
        if (napake_w > 0):
            warning(Opis_Napake_w, 1)
        if (napake_i > 0):
            info(Opis_Napake_i, 1)


    except Exception, e:
        debug.TraceDbg("Napaka pri poizvedovanju opozorilnih znakov!", e.message.ToString(), "Warning")
        stop("Glava spremnega lista ni izpolnjena!", 1)
        
#######################
# Obdelovanje izdelka #
#######################


            


def preglednapake(sender, args):
    if (debug.IsVisible == 0):
        debug.Show() 
    debug.TraceDbg("INFO", obrazec.image_info.Tag.ToString(), "Info")

def info(message = '', show=0):
    if (show):
        obrazec.image_info.Visibility = System.Windows.Visibility.Visible
        obrazec.image_info.ToolTip = '%s' %(message);
    else: 
        obrazec.image_info.Visibility = System.Windows.Visibility.Hidden
        obrazec.image_info.ToolTip = ''

def stop(message = '', show=0):
    if (show):
        obrazec.image_stop.Visibility = System.Windows.Visibility.Visible
        obrazec.image_stop.ToolTip = '%s' %(message);
    else: 
        obrazec.image_stop.Visibility = System.Windows.Visibility.Hidden
        obrazec.image_stop.ToolTip = '';

def warning(message = '', show=0):
    if (show):
        obrazec.image_warning.Visibility = System.Windows.Visibility.Visible
        obrazec.image_warning.ToolTip = '%s' %(message);
    else: 
        obrazec.image_warning.Visibility = System.Windows.Visibility.Hidden
        obrazec.image_warning.ToolTip = ''

def brisiznake():
    obrazec.label1_procesna_vobdelavi.Content = "n/a"
    obrazec.label1_serijska_vobdelavi.Content = "n/a"
    obrazec.label1_rezultat_vobdelavi.Content = "n/a"
    stop()
    warning()
    info()


def vhosopombe(sender, args):
    form = MyForm()
    form.Show()


def click_PASS(sender, args):
    try:
        global stevec_poizvedb
        if (stevec_poizvedb > 0):
            obrazec.label_status.Content = "Sistemske napake. Pocakaj da se poizvedbe koncajo. Vpis ni mozen!"
            return
        if (obrazec.label1_procesna_vobdelavi.Content.ToString() == "n/a"):
            obrazec.label_status.Content = "Nobena procesna ni v obdelavi"
            return
        if (obrazec.image_stop.IsVisible == 1):
            obrazec.label_status.Content = "Sistemske napake. STOP: Vpis ni mozen!"
            return
        global ID_izdelka
        global gl_insert_stavek
        insert_stavek = ("INSERT INTO SPREMNILISTIZDELKA (PROCESNA, SERIJSKA, NALOG, DATUM, OPERACIJA, OPERATER, REZULTAT, TEST) VALUES ('%s', '%s', '%s', CURRENT_TIMESTAMP, '%s', %s, %s, '%s'); SELECT SCOPE_IDENTITY();"
                         %(obrazec.label1_procesna_vobdelavi.Content, obrazec.label1_serijska_vobdelavi.Content, obrazec.comboBox_delnalogi.SelectedItem.ToString(),
                           obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_operaterji.SelectedItem.ToString().Substring(0, obrazec.comboBox_operaterji.SelectedItem.ToString().IndexOf('\t')),
                           0, obrazec.label1_rezultat_vobdelavi.Content))
        print "global stavek %s" %gl_insert_stavek
        print "navadn stavek %s" %insert_stavek
        if (gl_insert_stavek == insert_stavek):
            obrazec.label_status.Content = "Sistemske napake. Vpis je ze bil izveden!"
            return
        gl_insert_stavek = insert_stavek

        ID = poizvedbaPRIS(insert_stavek, "{}")
        osvezi_kolicine()
        if (ID != None):
            ID_izdelka = ID[0]
            obrazec.label_status.Content = 'Izdelek je vpisan kot PASS'
            preveriProcesnaVDN(obrazec.label1_procesna_vobdelavi.Content, 0)
        else:
            stop("NI ID-ja", 1)
            Windows.MessageBox.Show("Ni ID-ja!", "Vpis v bazo ni uspel!", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)
    except Exception, e:
        stop("Napaka pri vpisu! %s" %e.message.ToString(), 1)
        Windows.MessageBox.Show(e.message.ToString(), "Vpis v bazo ni uspel!", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)


def click_FAIL(sender, args):
    try:
        global stevec_poizvedb
        if (stevec_poizvedb > 0):
            obrazec.label_status.Content = "Sistemske napake. Pocakaj da se poizvedbe koncajo. Vpis ni mozen!"
            return
        if (obrazec.label1_procesna_vobdelavi.Content.ToString() == "n/a"):
            obrazec.label_status.Content = "Nobena procesna ni v obdelavi"
            return
        if (obrazec.image_stop.IsVisible == 1):
            obrazec.label_status.Content = "Sistemske napake. STOP: Vpis ni mozen!"
            return
        obrazec.label_status.Focus() 
        global ID_izdelka
        global gl_insert_stavek
        insert_stavek = ("INSERT INTO SPREMNILISTIZDELKA (PROCESNA, SERIJSKA, NALOG, DATUM, OPERACIJA, OPERATER, REZULTAT, TEST) VALUES ('%s', '%s', '%s', CURRENT_TIMESTAMP, '%s', %s, %s, '%s'); SELECT SCOPE_IDENTITY();"
                         %(obrazec.label1_procesna_vobdelavi.Content, obrazec.label1_serijska_vobdelavi.Content, obrazec.comboBox_delnalogi.SelectedItem.ToString(),
                           obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_operaterji.SelectedItem.ToString().Substring(0, obrazec.comboBox_operaterji.SelectedItem.ToString().IndexOf('\t')),
                           2, obrazec.label1_rezultat_vobdelavi.Content))
        if (gl_insert_stavek == insert_stavek):
            obrazec.label_status.Content = "Sistemske napake. Vpis je ze bil izveden!"
            return
        gl_insert_stavek = insert_stavek

        ID = poizvedbaPRIS(insert_stavek, "{}")
        if (ID != None):
            ID_izdelka = ID[0]
            obrazec.label_status.Content = 'Izdelek je vpisan kot FAIL'
            preveriProcesnaVDN(obrazec.label1_procesna_vobdelavi.Content, 0)
        else:
            stop("NI ID-ja", 1)
            Windows.MessageBox.Show("Ni ID-ja!","Vpis v bazo ni uspel!",  Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)
        osvezi_kolicine()
    except Exception, e:
        stop("Napaka pri vpisu! %s" %e.message.ToString(), 1)
        Windows.MessageBox.Show(e.message.ToString(), "Vpis v bazo ni uspel!", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)                    

def click_VPISINAPAKO(sender, args):  # vpis napake
    try:
        global stevec_poizvedb
        if (stevec_poizvedb > 0):
            obrazec.label_status.Content = "Sistemske napake. Pocakaj da se poizvedbe koncajo. Vpis ni mozen!"
            return
        if (obrazec.label1_procesna_vobdelavi.Content.ToString() == "n/a"):
            obrazec.label_status.Content = "Nobena procesna ni v obdelavi"
            return
        if (obrazec.image_stop.IsVisible == 1):
            obrazec.label_status.Content = "Sistemske napake. STOP: Vpis ni mozen!"
            return
        obrazec.label_status.Focus() 
        global ID_izdelka
        if (ID_izdelka == None):
            ID_izdelka = 0
        ID_napake = obrazec.comboBox_napake_napake.Tag[obrazec.comboBox_napake_napake.SelectedIndex]

        global gl_insert_stavek
        insert_stavek = ("INSERT INTO SPREMNILISTNAPAK (PROCESNA, OPERACIJA, OPERATER, POZICIJA, NAPAKA, OPIS, ID_IZDELEK) VALUES ('%s', '%s', %s, '%s', %s, '%s', %s); SELECT SCOPE_IDENTITY();"
                         %(obrazec.label1_procesna_vobdelavi.Content,  obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_operaterji.SelectedItem.ToString().Substring(0, obrazec.comboBox_operaterji.SelectedItem.ToString().IndexOf('\t')),
                           obrazec.comboBox_pozicije_napake.SelectedItem.ToString(), ID_napake, ID_izdelka, ID_izdelka))
        if (gl_insert_stavek == insert_stavek):
            obrazec.label_status.Content = "Sistemske napake. Vpis je ze bil izveden!"
            return
        gl_insert_stavek = insert_stavek

        ID = poizvedbaPRIS(insert_stavek, "{}")
        if (ID != None):
            obrazec.label_status.Content = 'Napaka %s je vpisana' %ID[0]
            preveriProcesnaVDN(obrazec.label1_procesna_vobdelavi.Content, 0)
        else:
            stop("NI ID-ja", 1)
            Windows.MessageBox.Show("Ni ID-ja!", "Vpis v bazo ni uspel!", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)

        # V karanteno
        if (obrazec.checkBox_izloci.IsChecked == 1):
            ID = poizvedbaPRIS("INSERT INTO SPREMNILISTIZDELKA (PROCESNA, SERIJSKA, NALOG, DATUM, OPERACIJA, OPERATER, REZULTAT, TEST) VALUES ('%s', '%s', '%s', CURRENT_TIMESTAMP, '%s', %s, %s, '%s'); SELECT SCOPE_IDENTITY();"
                             %(obrazec.label1_procesna_vobdelavi.Content, obrazec.label1_serijska_vobdelavi.Content, obrazec.comboBox_delnalogi.SelectedItem.ToString(), 
                               obrazec.comboBox_operacije.SelectedItem.ToString().Substring(0, obrazec.comboBox_operacije.SelectedItem.ToString().IndexOf('\t')), obrazec.comboBox_operaterji.SelectedItem.ToString().Substring(0, obrazec.comboBox_operaterji.SelectedItem.ToString().IndexOf('\t')),
                               5, obrazec.label1_rezultat_vobdelavi.Content), "{}")
            if (ID != None):
                ID_izdelka = ID[0]
                obrazec.label_status.Content = 'Izdelek je vpisan kot FAIL'
            else:
                stop("NI ID-ja", 1)
                Windows.MessageBox.Show("Ni ID-ja!","Vpis v bazo ni uspel!",  Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)
            osvezi_kolicine()

    except Exception, e:
        stop("Napaka pri vpisu! %s" %e.message.ToString(), 1)
        obrazec.label_status.Focus() 
        Windows.MessageBox.Show(e.message.ToString(), "Vpis v bazo ni uspel!", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)        

def init():
    nasvet_btn = System.Windows.Controls.Button()
    nasvet_btn.Content = "STATISTIKA"
    nasvet_btn.Height = 24
    obrazec.stackPanel2.Children.Add(nasvet_btn)
    nasvet_btn.Click += nasvet_click

    obrazec.button_skripta.Visibility = System.Windows.Visibility.Hidden
    lb_1 = Label()
    lb_1.Content = "NALOG"
    lb_1.Margin = System.Windows.Thickness(140, 240, 25, 5)
    obrazec.uiGridMain.Children.Add(lb_1)
    lb_2 = Label()
    lb_2.Content = "PASS"
    lb_2.Margin = System.Windows.Thickness(140, 252, 25, 5)
    obrazec.uiGridMain.Children.Add(lb_2)
    lb_3 = Label()
    lb_3.Content = "FAIL"
    lb_3.Margin = System.Windows.Thickness(140, 264, 25, 5)
    obrazec.uiGridMain.Children.Add(lb_3)
    lb_4 = Label()
    lb_4.Content = "KARAN"
    lb_4.Margin = System.Windows.Thickness(140, 276, 25, 5)
    obrazec.uiGridMain.Children.Add(lb_4)
    lb_5 = Label()
    lb_5.Content = "TODO"
    lb_5.Margin = System.Windows.Thickness(140, 288, 25, 5)
    obrazec.uiGridMain.Children.Add(lb_5)

    global lb_nalog
    global lb_pass
    global lb_fail
    global lb_out
    global lb_todo
    lb_nalog = Label()
    lb_nalog.Content = "n/a"
    lb_nalog.FontWeight = System.Windows.FontWeights.Bold
    lb_nalog.Foreground = System.Windows.Media.Brushes.Black
    lb_nalog.Margin = System.Windows.Thickness(180, 240, 25, 5)
    obrazec.uiGridMain.Children.Add(lb_nalog)
    lb_pass = Label()
    lb_pass.Content = "n/a"
    lb_pass.FontWeight = System.Windows.FontWeights.Bold
    lb_pass.Foreground = System.Windows.Media.Brushes.Green
    lb_pass.Margin = System.Windows.Thickness(180, 252, 25, 5)
    obrazec.uiGridMain.Children.Add(lb_pass)
    lb_fail = Label()
    lb_fail.Content = "n/a"
    lb_fail.FontWeight = System.Windows.FontWeights.Bold
    lb_fail.Foreground = System.Windows.Media.Brushes.Orange
    lb_fail.Margin = System.Windows.Thickness(180, 264, 25, 5)
    obrazec.uiGridMain.Children.Add(lb_fail)
    lb_out = Label()
    lb_out.Content = "n/a"
    lb_out.FontWeight = System.Windows.FontWeights.Bold
    lb_out.Foreground = System.Windows.Media.Brushes.Red
    lb_out.Margin = System.Windows.Thickness(180, 276, 25, 5)
    obrazec.uiGridMain.Children.Add(lb_out)
    lb_todo = Label()
    lb_todo.Content = "n/a"
    lb_todo.FontWeight = System.Windows.FontWeights.Bold
    lb_todo.Foreground = System.Windows.Media.Brushes.Blue
    lb_todo.Margin = System.Windows.Thickness(180, 288, 25, 5)
    obrazec.uiGridMain.Children.Add(lb_todo)



def nasvet_click(sender, args):  
    print "TODO"
    prenos()
#
#   M A I N
#

lb_nalog = None
lb_pass = None
lb_fail = None
lb_out = None
lb_todo = None
obrazec.Dispatcher.Invoke(DispatcherPriority.Background, Action(init))
try:
    nadgradnja.nadgradi()
except Exception, e:
    debug.TraceDbg("Nadgradnja ni uspela!", "%s" %(e.message.ToString()), "Warning")
serialP = Regex("P[0-9]{8}[A|B]")
serialZ = Regex("Z[0-9]{8}[G|H]")
debug.textBox_logging.TextChanged += hookerchangedP
debug.textBox_logging.TextChanged += hookerchangedZ
obrazec.Dispatcher.Invoke(DispatcherPriority.Background, Action(StartHooker))

obrazec.button_opombe.Click += vhosopombe
obrazec.Dispatcher.Invoke(DispatcherPriority.Background, Action[object](seznam_izdelkov), poizvedbaNTPE("SELECT DISTINCT `Program` FROM `sledljivost`.`asysaba04` ORDER BY `Program`;", "{Program}"))
obrazec.comboBox_izdelki.SelectionChanged += izdelek_changed
obrazec.comboBox_delnalogi.SelectionChanged += dn_changed
obrazec.comboBox_operacije.SelectionChanged += operacije_changed
obrazec.Dispatcher.Invoke(DispatcherPriority.Background, Action[object](seznam_operacij), poizvedbaPRIS("SELECT [ATE], [ZNAK] FROM [KAKOVOST].[dbo].[SEZATE] ORDER BY [ID];", "{ZNAK}\t{ATE}"))
obrazec.Dispatcher.Invoke(DispatcherPriority.Background, Action[object](seznam_operaterjev), poizvedbaPRIS("SELECT [ID], [KONTROLOR], [IME], [DELSTEV] FROM [KAKOVOST].[dbo].[SEZKONTROLORJEV] WHERE [STATUS] = 0 ORDER BY [IME];", "{ID}\t{KONTROLOR} {IME}"))
obrazec.comboBox_pozicije_napake.SelectionChanged += pozicija_napake_changed
obrazec.textBox_dummyprocesna.TextChanged += dummyprocesna_changed
obrazec.comboBox_napake_napake.SelectionChanged += napake_napake_changed
obrazec.button_green.Click += click_PASS
obrazec.button_red.Click += click_FAIL
obrazec.button_vpisi.Click += click_VPISI

def rezultat_testa(serijska, res):
    if (serijska != obrazec.label1_serijska_vobdelavi.Content.ToString()):
        Windows.MessageBox.Show("Serijska testiranca se ne ujema s spremnim listom!", "Rezultat testiranja", Windows.MessageBoxButton.OK, Windows.MessageBoxImage.Error)
    else:
        obrazec.label1_rezultat_vobdelavi.Content = res

class MyTCPHandler(SocketServer.BaseRequestHandler):
    def handle(self):
        try:
            self.data = self.request.recv(1024).strip()
            serijska = self.data.ToString().Split(' ')[0]
            rezultat = self.data.ToString().Split(' ')[1]
        except Exception, e:
            serijska = "n/a"
            rezultat = "n/a"
        debug.TraceDbg("%s wrote:" % self.client_address[0], "String: %s -> SERIAL: %s RESULT: %s" %(self.data, serijska, rezultat), "Info")
        obrazec.Dispatcher.Invoke(DispatcherPriority.Background, Action[object, object](rezultat_testa), serijska, rezultat)
       


HOST, PORT = "localhost", 9999

# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

barva_obrazca('None')
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()